# RANDOM DRAFT SCRIPT
# This script performs a random draft for any team that does not have a roster
# by the time the league starts, or if the league creator selected a random draft.
# 
# Script must pass in the league ID to perform the draft for.
#
# Created on December 9, 2009 by Caleb Goff

#!/bin/bash
set +x

# Store the league ID
league=$1

# Retrieve teams in league
mysql FBT52009 -ubroomball -pbroomball -horion.csl.mtu.edu > draft_teams.txt <<EOFMYSQL
SELECT TEAM_ID FROM TEAMS WHERE LEAGUE_ID='$league'
EOFMYSQL

# Declare arrays to store data
count=0
declare -a TEAMS
declare -a PLAYERS

# Read in the teams from the query into the TEAMS array
for line in $(sed '1d' draft_teams.txt)
do
    TEAMS[($count)]=$line
    ((count++))
done

# Delete file containing team IDs since it's now stored in the array
rm -f draft_teams.txt

ELEMENTS=${#TEAMS[@]}

#Cycle through each team in the league
for (( j=0;j<($ELEMENTS);j++)); do
    
    # Check if the team has an active roster
    mysql FBT52009 -ubroomball -pbroomball -horion.csl.mtu.edu > drafted.txt <<EOFMYSQL
    SELECT COUNT(TEAM_ID) FROM ROSTER WHERE TEAM_ID='${TEAMS[j]}'
EOFMYSQL

    roster=$(sed '1d' drafted.txt)

    # If the team does not have a roster, randomly draft a roster for them
    if [ $roster -eq 0 ] ; then

        count=0

        # Retrieve Free Agent players
        mysql FBT52009 -ubroomball -pbroomball -horion.csl.mtu.edu > rdraft.txt <<EOFMYSQL
        SELECT PLAYER_ID FROM PLAYERS
        WHERE PLAYER_ID NOT IN ( SELECT PLAYER_ID FROM ROSTER WHERE TEAM_ID IN ( SELECT TEAM_ID FROM TEAMS WHERE          
        LEAGUE_ID='$league' ) )
EOFMYSQL
        
        # Store players in an array
        for line in $(sed '1d' rdraft.txt)
        do
            PLAYERS[($count)]=$line
            ((count++))
        done

        count2=1
        position=1

        # Cycle through 10 times and add 10 random players
        for (( i=0;i<10;i++)); do
            if [ $count2 -gt 6 ] ; then
                position=-1
            fi
            rand=$[ ( $RANDOM % $count ) + 1 ]
            echo ${PLAYERS[$rand]}
            mysql FBT52009 -ubroomball -pbroomball -horion.csl.mtu.edu <<EOFMYSQL
            INSERT INTO ROSTER (TEAM_ID, POSITION, PLAYER_ID) VALUES('${TEAMS[$j]}','$position','${PLAYERS[$rand]}')
EOFMYSQL
            ((count2++))
        done
    fi

done

mysql FBT52009 -ubroomball -pbroomball -horion.csl.mtu.edu << EOFMYSQL
UPDATE LEAGUES SET DRAFT_DONE = 1 WHERE LEAGUE_ID = '$league'
EOFMYSQL

# Remove temporary files
rm -f drafted.txt
rm -f rdraft.txt
